/**
 * Created on 2007-05-23 13:32
 */
package tools.xmlTools;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * @author David Wallin
 * 
 * A wrapper class for xml reading and writing
 */
public class XMLTool
{
	/**
	 * The parser factory
	 */
	private DocumentBuilderFactory		m_Factory;
	
	/**
	 * Default constructor, initializes the path to "". This means that nothing will be
	 * added to passed file names when calling methods requiring such
	 */
	public XMLTool()
	{
		m_Factory = DocumentBuilderFactory.newInstance();
	}
	
	/**
	 * Creates and returns a new XMLReadOnlyDocument from the given file url
	 * 
	 * @param documentLocation the location of the xml document on the internet
	 * @return the XMLReadOnlyDocument wrapping the found xml file
	 * @throws Exception if something fails
	 */
	public XMLReadOnlyDocument getDocument(String documentLocation) throws Exception
	{
		Document				document = null;
		boolean					parsed = false;
		String					error = "unknown error in XMLTool";
		
		try
		{
			DocumentBuilder documentBuilder = null;
			documentBuilder = m_Factory.newDocumentBuilder();
			document = documentBuilder.parse(documentLocation);
			parsed = true;
		}
		catch(ParserConfigurationException e)
		{
			error = "ParserConfigurationException in XMLTool exception!\n\n" + e.getMessage();
		}
		catch(SAXException e)
		{
			error = "SAXException in XMLTool exception!\n\n" + e.getMessage();
		}
		catch(IOException e)
		{
			error = "IOException in XMLTool exception!\n\n" + e.getMessage();
		}
		
		if(!parsed)
		{
			throw new Exception(error);
		}
		
		return new XMLReadOnlyDocument(documentLocation, document);
	}
}
